package main

import (
	"fmt"
	"sync"
	"time"
)

var cond *sync.Cond
var mutex sync.Mutex

var cond_five *sync.Cond
var mutex_five sync.Mutex
var wg sync.WaitGroup

var five [5]int
var five_count int
var customer_index int = 0

func productor() {
	index := 0
	prodnum := 1000
	for {
		mutex.Lock()
		time.Sleep(time.Millisecond * 100)
		five[index] = prodnum
		fmt.Println("Productor num=======", prodnum)
		prodnum++
		five_count++
		index = (index + 1) % 5
		cond.Signal() //通知消费者
		mutex.Unlock()
		if five_count == 5 { //限制生产者不能随意生产
			mutex_five.Lock()
			cond_five.Wait() //等待消费者来唤醒
			mutex_five.Unlock()
		}
		//time.Sleep(time.Millisecond)

	}

	wg.Done()
}

func customer(num int) {

	for {
		mutex.Lock()
		cond.Wait() //等待生产者唤醒
		if five_count > 0 {
			time.Sleep(time.Millisecond * 10)
			fmt.Println(num, "customer num=======", five[customer_index])

			customer_index = (customer_index + 1) % 5
			five_count--
			cond_five.Signal() //通知生产者
		}
		mutex.Unlock()
	}
	wg.Done()
}

func main() {
	//创建条件变量
	cond = sync.NewCond(&mutex)
	cond_five = sync.NewCond(&mutex_five)
	wg.Add(3)
	//启动1个生产者2个消费者
	go productor()
	go customer(1)
	go customer(2)
	wg.Wait()
}
